<?php
/**
 * 购物车控制器
 * @author e5
 *
 */
class CartController extends CommonController{
	/**
	 * 购物车列表
	 */
	public function index() {
		$cartData = Cart::getAllData();
		$gadb = K("GoodsAttr");
		foreach ($cartData['goods'] as $k=>$v){
			//处理商品属性
			foreach (explode(",", $v['combine']) as $c){
				$cartData['goods'][$k]['attrs'][] = $gadb->where("gaid={$c}")->getField("gavalue");
			}
			$cartData['goods'][$k]['attrs'] = implode(",", $cartData['goods'][$k]['attrs']);
			//处理价格
			$cartData['goods'][$k]['total'] = number_format($cartData['goods'][$k]['total'], 2);
		}
		$cartData['total'] = number_format(intval($cartData['total']),2);
		$this->assign("cartData",$cartData);
		$this->dis("mycart");
	}
	/**
	 * 添加购物车
	 */
	public function add() {
		if (!IS_AJAX) return;
		$combine = explode("_", Q("post.param"));
		$where = "";
		foreach ($combine as $v){
			$where .= "combine LIKE '%{$v}%' AND ";
		}
		$where = rtrim($where, "AND ");
		$gid = Q("post.goodsid",0,"intval");
		//查询商品数据
		$goodsData = M()->field("g.gname,g.gshopprice,g.gpic,gl.*")->join("__goods__ g JOIN __goodslist__ gl ON g.gid=gl.vshop_goods_gid")->where("gl.vshop_goods_gid={$gid} AND {$where}")->find();
		//判断库存
		if (Q("post.goodsnum",0,"intval") > $goodsData['glinventory']){
			echo 0;exit();
		}
		//处理附加价格
		$combine = implode(",", $combine);
		$addPrice = K("GoodsAttr")->where("gaid IN ({$combine})")->sum('addprice');
		$goodsData['gshopprice'] = number_format($goodsData['gshopprice']+intval($addPrice),2);
		//添加到购物车
		$data = array(
				"id"=>$goodsData['glid'],
				'gid'=>$gid,
				"name"=>$goodsData['gname'],
				"gpic"=>$goodsData['gpic'],
				'num'=>Q("post.goodsnum",0,"intval"),
				"price"=>$goodsData['gshopprice'],
				"combine"=>$combine
		);
		Cart::add($data);
		$this->ajax(array('totalnums'=>Cart::getTotalNums(),'totalprice'=>Cart::getTotalPrice()));
	}
	/**
	 * 增加购物车中商品的数量
	 */
	public function addNum(){
		if (!IS_AJAX) return;
		$sid = Q("post.sid");
		$cartData = Cart::getAllData();
		$glid = $cartData['goods'][$sid]['id'];
		$newNum = $cartData['goods'][$sid]['num']+1;
		//判断库存是否充足
		if ($newNum > K("GoodsList")->where("glid={$glid}")->getField("glinventory")){
			echo 0;exit();
		}
		$data = array(
				'sid'=>$sid,
				'num'=>$newNum
		);
		Cart::update($data);
		echo $newNum;exit();
	}
	/**
	 * 减少购物车中商品的数量
	 */
	public function decNum(){
		if (!IS_AJAX) return;
		$sid = Q("post.sid");
		$cartData = Cart::getAllData();
		$glid = $cartData['goods'][$sid]['id'];
		$newNum = $cartData['goods'][$sid]['num']-1;
		//判断商品量是否为0
		if ($newNum <= 0){
			Cart::del($sid);
			echo 0;exit();
		}
		$data = array(
				'sid'=>$sid,
				'num'=>$newNum
		);
		Cart::update($data);
		echo $newNum;exit();
	}
}